<template>
	<view>
		<view>
			<view style="
            position: fixed;
            z-index: 1;
            bottom: 370rpx;
            right: 0;">
				<image @click="location" src="/static/location.png" style="width: 40px;height: 40px;"></image>
			</view>
		</view>
		<view class="search" style="">
			<!-- <picker @change="bindPickerChange" :value="arrayTypeIndex" :range="arrayType">
				<view class="uni-input">{{arrayType[arrayTypeIndex]}}</view>
			</picker> -->
			<!-- <text class="iconfont" style="font-size: 30rpx;">&#xe618;</text> -->
			<view class="input" style="flex-direction: row;align-items: center;justify-content: space-between;">
				<input style="width: 450rpx;font-size: 30rpx;" class="" type="text" placeholder="搜索设备编码或设备所在地址"
					confirm-type="search" v-model="keyword" @confirm="bindSearchClick" />
				<text v-if="keyword" class="iconfont" style="font-size: 40rpx;" @click="clearKeyword">&#xe60f;</text>
				<text style="margin-right: 20rpx;" @click="bindSearchClick">搜索</text>
			</view>
		</view>
		<map id="map" ref="map" :style="'width: ' + width + '; height: ' + height + ';'" :scale="map.scale"
			@regionchange="regionchange" showLocation @updated="updated" :latitude="map.latitude"
			:longitude="map.longitude"  :markers="covers" @callouttap="de" @markertap="markertClick">
		</map>
		
		<view v-if="listIndex>=0&&list[listIndex].ename" class="info" style="">
			<view class="">
				<text style="font-weight: 800;">{{list[listIndex].ename}}</text>
				<text style="color: #7c7c7c;font-size: 30rpx;margin-top: 14rpx;width: 400rpx;">{{list[listIndex].address}}</text>
			</view>
			<view
				style="position: absolute;right: 20rpx;top: 70rpx;width: 140rpx;height: 70rpx;background-color: #1D9FFA;border-radius: 20rpx;align-items: center;justify-content: center;">
				<text style="color: #FFFFFF;" @click="actionSheet(list[listIndex])">导航</text>
			</view>
		</view>
		<view v-if="isMarkers" class="search-box">
			<scroll-view :scroll-y="true" class="scroll" @scrolltolower='refresh'>
				<view class="list" v-for="(item, index) in listMarkers" :key="index" @click="bindPointClick(index)">
					<view class="top">
						<view class="left">
							<view>
								<text class="name">{{item.ename}}</text>
							</view>
							<view>
								<text class="detail">{{item.address}}</text>
							</view>
						</view>
						<view
							style="position: absolute;right: 20rpx;top: 10rpx;width: 100rpx;height: 50rpx;background-color: #1D9FFA;border-radius: 20rpx;align-items: center;justify-content: center;">
							<text style="color: #FFFFFF;font-size: 30rpx;" @click="actionSheet(item)">导航</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<image :style="`top:${(windowHeight-90)/2}px`" style="position: fixed;left: 330rpx;z-index:1000;width: 90rpx;height: 90rpx;" src="/static/icon_location@3x.png" mode=""></image>
	</view>
</template>

<script>
	// import zjMarker()
	import gcoord from 'gcoord';
	let mapSearch = weex.requireModule('mapSearch')
	import {
		showInfoToast,
		doGet,
		doPostJson,
		doPostForm,
	} from '@/common/util.js'
	export default {
		data() {
			return {
				keyword: '',
				latitude: '30',
				arrayType: ['地址', '设备'],
				arrayTypeIndex: 0,
				arrayTypeUrl: [],
				longitude: '120',
				height: '500px',
				width: '500px',
				map: {
					scale: 13,
					latitude: 39.909,
					longitude: 116.39742
				},
				covers: [],
				isMarkers:false,
				listIndex: -1,
				list:[],
				listMarkers: [],
				load: true,
				focus: false,
				MapContext:null,
				windowHeight:0
			};
		},
		created() {
			var domModule = weex.requireModule("dom");
			domModule.addRule('fontFace', {
				'fontFamily': 'iconfont',
				'src': "url(\'https://at.alicdn.com/t/font_2748372_jh01y2d9fhc.ttf?t=1629460162472\')"
			})
			this.windowHeight =  uni.getSystemInfoSync().windowHeight
			console.log(this.windowHeight)
		},
		onLoad() {
			// 创建地图上下文
			this.MapContext = uni.createMapContext('map', this);

			uni.getSystemInfo({
				success: res => {
					this.height = res.windowHeight + 'px';
					this.width = res.windowWidth + 'px';
				}
			});
			this.location();
			// map.translateMarker
		},
		methods: {
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.arrayTypeIndex = e.detail.value
			},
			clearKeyword(){
				this.keyword = ""
			},
			//搜索设备
			bindSearchClick() {
				doGet(`/api/yun-bag/equipment/search-equipment/${this.keyword}?pageNum=1&pageSize=100`, {}, {}, false).then(res => {
					console.log('加载数据',res.data)
					if(res.data.length>0){
						this.listMarkers = res.data;
						this.isMarkers = true
					}else {
						showInfoToast("没有查到设备信息");
					}
				}).catch(error => {
					console.log(error)
				})
			},
			actionSheet(item) {
				console.log(item)
				// #ifdef APP-PLUS
				uni.showActionSheet({
					itemList: ['百度地图', '高德地图'],
					success: res => {
						if (res.tapIndex == 0) {
							if (plus.os.name == "Android") {
								let bdMode = "driving";//默认汽车导航
								let bdapp = "baidumap://map/direction?origin=我的位置&destination=name:" + item.address + "|latlng:" + item.lat.toFixed(6) + "," +
									item.lng.toFixed(6) + "&coord_type=gcj02&mode=" + bdMode + "&src=uniapp";
								this.showModal(bdapp,"您未安装百度地图,请安装后在导航","com.baidu.BaiduMap");
							} else {
								
							}
							
						} else if (res.tapIndex == 1) {
							if (plus.os.name == "Android") {
								let amapMode = 0;//默认汽车导航
								let amapuri = "amapuri://route/plan/?sourceApplication=uniapp&dlat="+item.lat.toFixed(6)+"&dlon="+item.lng.toFixed(6)+"&dname="+item.address+"&t="+amapMode;	
								this.showModal(amapuri,"您未安装百度地图,请安装后在导航","com.baidu.BaiduMap");
							}else {
								
							}
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
				// #endif
			},
			showModal(bdapp,content,packages){
				plus.runtime.openURL(encodeURI(bdapp), res => {
					uni.showModal({
					    title: '提示',
					    content: content,
						cancelText:"否",
						confirmText:"立即安装",
					    success: function (res1) {
							console.log(res1)
					        if (res1.confirm) {
					            plus.runtime.openURL("market://details?id="+packages);
					        } else if (res1.cancel) {
					            console.log('用户点击取消');
					        }
					    }
					});
				});
			},
			//根据东北 西南经纬度 以及后台返回标记点 格式化成小程序marker点
			updated() {
				// console.log('渲染完成');
			},
			// 当视野发生改变
			regionchange(e) {
				// console.log('视野发生变化');
				if (e.type == 'end') {  //在安卓中是 end 事件
					this.getCenterLanLat() 
				}else if(e.type =='regionchange'){ // 在ios中是 regionchange
					this.getCenterLanLat() 
				}
			},
			// 获取当前地图中心的经纬度
			getCenterLanLat() {
				this.MapContext.getCenterLocation({
					type: 'gcj02',
					success: (res) => {
						let address = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						this.queryFacility(address.latitude,address.longitude);
						// this.$emit('longLatDetail', address)
					},
					fail: (err) => {
						// console.log('获取当前地图中心的经纬度2', err);
					}
				})
			},
			//定位当前
			location() {
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						// console.log('地址获取成功,切换到目标点nvue', res);
						this.MapContext.moveToLocation({
							latitude: res.latitude,
							longitude: res.longitude
						})
						this.latitude = res.latitude
						this.longitude = res.longitude
						
						// this.getList(res.latitude,res.longitude);
					},
					fail: () => {
						console.log('地理位置获取失败');
					}
				});
			},
			queryFacility(latitude,longitude){
				let markers = {}
				let markersArr = []
				doGet(`/api/yun-bag/equipment/nearby-equipment/${longitude}@${latitude}`, {}, {}, true).then(res => {
					// if (res.data.code === this.$ResponseStatus.OK) {
						
					// }
					if(res.data.length>0){
						this.list = res.data
						// this.list.unshift(markers)
						this.list.forEach((item, index) => {
							markers = {
								id: index,
								latitude: item.lat.toFixed(6),
								longitude: item.lng.toFixed(6),
								iconPath: "/static/icon_map_promotion@3x.png",
								width: 60,
								height: 60,
								facilityId:item.id,
								data:JSON.stringify(item)
								// callout: { //自定义标记点上方的气泡窗口 点击有效  
								// 	content: item.address, //文本
								// 	color: '#ffffff', //文字颜色
								// 	fontSize: 14, //文本大小
								// 	borderRadius: 2, //边框圆角
								// 	bgColor: '#00c16f', //背景颜色
								// 	display: 'ALWAYS', //常显
								// 	padding: 5 //气泡窗口的内间距
								// },
													
							}
							markersArr.push(markers)
						})
					}else {
						this.listIndex = -1
					}
					this.covers = markersArr
				}).catch(error => {
					console.log(error)
				})
			},
			markertClick(i) {
				let index = i.detail.markerId
				this.listIndex = index;
				this.isMarkers = false
			}
		}
	};
</script>

<style>
	.info {
		width: 650rpx;
		background-color: #FFFFFF;
		position: fixed;
		bottom: 40rpx;
		left: 50rpx;
		padding: 35rpx;
		border-radius: 17rpx;
		/* padding-top: 30rpx;
		padding-bottom: 30rpx;
		padding-left: 35rpx;
		padding-right: 35rpx; */
	}

	.search-box {
		width: 750rpx;
		height: 630rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #FFFFFF;
		z-index: 99;
		border-radius: 20rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		padding-top: 30rpx;
	}

	.search {
		position: fixed;
		z-index: 1;
		top: 0rpx;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		width: 750rpx;
		height: 120rpx;
		background-color: #FFFFFF;
	}

	.input {
		width: 660rpx;
		height: 80rpx;
		padding-left: 30rpx;
		line-height: 80rpx;
		background-color: #ececec;
		border-radius: 50rpx;
	}

	.scroll {
		height: 610rpx;
	}

	.list {
		flex-direction: column;
	}

	.top {
		flex-direction: row;
		align-items: center;
	}

	.left {
		width: 650rpx;
		flex-direction: column;
	}

	.name {
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}

	.hook {
		font-size: 26rpx;
	}

	.detail {
		font-size: 24rpx;
		color: #666666;
		margin-bottom: 10rpx;
	}

	.line {
		height: 1rpx;
		background-color: #CCCCCC;
		margin-bottom: 14rpx;
	}

	.iconfont {
		font-family: iconfont;
	}
</style>
